package com.shxy.rlzy.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shxy.rlzy.common.lang.Result;
import com.shxy.rlzy.entity.Role;
import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.service.IEmployeeUserService;
import com.shxy.rlzy.service.IRoleService;
import com.shxy.rlzy.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanhao
 * @since 2021-08-16
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {
    private IUserService userService;

    private IEmployeeUserService employeeUserService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public void setEmployeeUserService(IEmployeeUserService employeeUserService) {
        this.employeeUserService = employeeUserService;
    }

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 添加用户
     * @return
     */
    @GetMapping("/add")
    @PreAuthorize("hasAnyAuthority('sys:user:save')")
    public Result add() {
        return Result.succ();
    }

    /**
     * 刷新用户
     * @return
     */
    @GetMapping("/refresh")
    public Result refresh() {
        employeeUserService.refreshClerks(); // 刷新工资员
        return Result.succ();
    }

    /**
     * 编辑用户信息
     * @return
     */
    @GetMapping("/edit/{userId}")
    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    public Result edit(@PathVariable Long userId) {
        User user = userService.getById(userId);
        if(user == null) {
            return Result.fail("该用户不存在!");
        }
        return Result.succ(convert2Json(user));
    }

    /**
     * 修改密码
     * @param orgPwd
     * @param newPwd
     * @return
     */
    @PostMapping("/changePwd")
    public Result changePwd(String orgPwd, String newPwd) {
        // 获取用户账号和密码
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.getByUsername(username);
        if(!passwordEncoder.matches(orgPwd, user.getPassword())) {
            return Result.fail("原密码输入错误");
        }
        if(!userService.changePassword(username, newPwd)) {
            return Result.fail("修改密码失败");
        }
        return Result.succ("密码修改成功");
    }

    @PostMapping("/resetPwd/{userId}")
    @PreAuthorize("hasAnyAuthority('sys:user:resetpwd')")
    public Result resetPwd(@PathVariable Long userId) {
        if(userService.resetPassword(userId)) {
            return Result.succ("密码重置成功");
        }
        return Result.fail("密码重置失败");
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/info")
    public Result getUserInfo() {
        // 获取用户名
        String userName = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 根据用户名获取用户信息
        User user = userService.getByUsername(userName);

        JSONObject rs = JSONUtil.createObj();
        rs.set("id", user.getId());
        rs.set("username", userName);
        rs.set("avatar", user.getAvatar());
        return Result.succ(rs);
    }

    /**
     * 分页获取用户列表
     * @return
     */
    @GetMapping("/list/{current}/{size}")
    @PreAuthorize("hasAuthority('sys:user:list')")
    public Result list(@PathVariable int current, @PathVariable int size) {
        // 分页查询
        Page<User> pageUsers = userService.page(new Page<>(current, size));
        // 列表格式转换
        List<JSONObject> list = pageUsers.getRecords().stream().map(u -> convert2Json(u)).collect(Collectors.toList());
        // 构建返回对象
        JSONObject result = JSONUtil.createObj();
        result.set("users", list);
        result.set("total", pageUsers.getTotal());
        result.set("current", pageUsers.getCurrent());
        result.set("size", pageUsers.getSize());
        return Result.succ(result);
    }

    @PutMapping("/save/role")
    @PreAuthorize("hasAuthority('sys:user:update')")
    public Result save(@RequestBody User user) {
        // 保存角色信息
        if(userService.customSave(user)) {
            return Result.succ("保存用户信息成功!");
        }
        return Result.fail("保存用户信息失败!");
    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    public Result logout() {
        return Result.succ("退出登录");
    }

    /**
     * 删除用户信息
     * @param userId
     * @return
     */
    @DeleteMapping("/delete/{userId}")
    @PreAuthorize("hasAuthority('sys:user:delete')")
    public Result delete(@PathVariable Long userId) {
        // 无法删除自己
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.getById(userId);
        // 无法删除自己
        if(user.getUsername().equals(username)){
            return Result.fail("你无法删除自己");
        }
        // 无法删除超级管理员
        if(user.getStatu() == -1) {
            return Result.fail("无法删除超级管理员");
        }
        // 执行删除操作
        if(userService.removeById(userId)) {
            return Result.succ("删除用户成功!");
        }
        return Result.fail("删除用户失败!");
    }

    /**
     * 格式转换
     * @param user
     * @return
     */
    private JSONObject convert2Json(User user) {
        JSONObject o = JSONUtil.parseObj(user);
        o.remove("password");
        Role role = getRoleByUserId(user.getId());
        o.set("role", role.getName());
        return o;
    }

    /**
     * 查询用户的角色信息
     * @param userId
     * @return
     */
    private Role getRoleByUserId(Long userId) {
        return userService.getRoleByUserId(userId);
    }
}
